package com.wkm.chainchain.pbft.PBFTBlockchainNode;

import com.alibaba.fastjson.JSON;
import com.wkm.chainchain.pbft.common.PBFTMsgType;
import com.wkm.chainchain.pbft.msg.PBFTMsg;
import com.wkm.chainchain.pbft.node.MsgCollection;
import com.wkm.chainchain.pbft.node.Node;
import com.wkm.chainchain.pbft.p2p.PBFTClient;
import com.wkm.chainchain.pbft.p2p.PBFTServer;
import com.wkm.chainchain.websocket.Client;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.UUID;

import static com.wkm.chainchain.pbft.common.SimulationParameterConst.*;
import static com.wkm.chainchain.state.ConsensusNodeBuildState.*;


/**
 * PBFT主函数 通过输入确定共识节点还是消息发送端口 注意java虚拟机内存的设置 线程开太多容易爆栈 -Xms1024m -Xmx1024m
 */
@Slf4j
@Component
public class PBFTClientNode {

    static {
        returnToZero();
        clientStart();
    }

    public static void clientStart() {

        int port = CLIENT_PORT;
        PBFTServer.getInstance(port);
        //初始化当前节点
        Node node = Node.getInstance();
        node.setIndex(-1);
        node.setIp("127.0.0.1");
        node.setPort(port);

        setClientState(true);

        do {
            try {
                Thread.sleep(sleepTimeMills);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        } while (getServerRunningNum() < NODE_AMOUNT);

        try {
            Thread.sleep(sleepTimeMills * 2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        returnToZero();

        Client client = PBFTClient.getInstance();
        //与主节点建立连接
        client.connectPeer("ws://localhost:" + INITIAL_PORT);

        //发送消息，每隔10秒钟发送1次
        for (int i = 0; i < 10000; i++) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            PBFTMsg pbftMsg = new PBFTMsg();
            pbftMsg.setMsgType(PBFTMsgType.REQUEST.getCode());
            pbftMsg.setViewIndex(0);
            pbftMsg.setMsgIndex((long) i);
            pbftMsg.setMessage("TEST_BLOCKCHAIN");
            client.broadcast(JSON.toJSONString(pbftMsg));
        }

        log.info("共识结果: {}, 共识数量: {}", MsgCollection.reachedConsensusMsgList, MsgCollection.reachedConsensusMsgList.size());

    }
}


